package com.kintreda.service.sysjob.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kintreda.common.mybatis.entity.SysTask;
import com.kintreda.common.mybatis.service.ISysTaskService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class SysJobRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(SysJobRunner.class);

    @Autowired
    private ISysTaskService iTaskService;

    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    @Override
    public void run(String... args) {
        QueryWrapper<SysTask> queryWrapper = new QueryWrapper();
        queryWrapper.eq("status",1);
        List<SysTask> list = iTaskService.list(queryWrapper);
        if (ObjectUtils.isNotEmpty(list) && list.size()>0){
            list.forEach(x->{
                SchedulingRunnable task = new SchedulingRunnable(x.getBeanName(),x.getMethodName(), x.getMethodParams());
                cronTaskRegistrar.addCronTask(task,x.getCronExpression());
                x.setUpdateTime(LocalDateTime.now());
            });
            iTaskService.updateBatchById(list);
        }
    }
}
